﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketChatClient
{
    public partial class FrmSocketClient : Form
    {
        public FrmSocketClient()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            string str=txtMsg.Text.Trim();
            //把要发送的消息转为字节数组
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketCommunication.Send(buffer);
        }
        Socket socketCommunication;
        private void BtnStart_Click(object sender, EventArgs e)
        {
            //这里创建的是负责通信的socket
            socketCommunication = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(txtServer.Text);
            IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
            socketCommunication.Connect(point);
            ShowMsg("连接成功");
            Thread thread = new Thread(Receive);
            thread.IsBackground = true;
            thread.Start();
        }
        /// <summary>
        /// 不断的去接收服务端发过来的消息
        /// </summary>
        void Receive()
        {
            byte[] buffer = new byte[1024 * 1024 * 3];
            while (true)
            {               
                int r=socketCommunication.Receive(buffer);
                if(r==0)
                {
                    break;
                }
                int n = buffer[0];
                if(n==0)
                {
                    string s = Encoding.UTF8.GetString(buffer, 1, r-1);
                    ShowMsg(socketCommunication.RemoteEndPoint.ToString() + ":" + s);
                }
                else if(n==1)
                {
                    #region 第1种思路，使用文件流写
                    //SaveFileDialog sfd = new SaveFileDialog();
                    //sfd.InitialDirectory= @"C:\Users\lenovo\Desktop";
                    //sfd.Title = "请选择要保存文件的位置";
                    //sfd.Filter = "所有文件|*.*|word文档|*.doc";
                    //sfd.ShowDialog(this);
                    //string path = sfd.FileName;
                    //using(FileStream fsWrite=new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write))
                    //{
                    //    fsWrite.Write(buffer, 1, r - 1);
                    //}
                    //MessageBox.Show("保存成功");
                    #endregion
                    #region 第2中实现思路 通过File.WriteAllBytes
                using(SaveFileDialog sfd=new SaveFileDialog())
                    {
                        sfd.InitialDirectory = @"C:\Users\lenovo\Desktop";
                        sfd.Title = "请选择要保存文件的位置";
                        sfd.Filter = "所有文件|*.*|word文档|*.doc";
                        sfd.DefaultExt = "doc";
                        if(sfd.ShowDialog(this)!=DialogResult.OK)
                        {
                            return;
                        }
                        byte[] newBuffer = new byte[r - 1];
                        Buffer.BlockCopy(buffer, 1, newBuffer, 0, r - 1);
                        File.WriteAllBytes(sfd.FileName,newBuffer);
                        MessageBox.Show("保存成功");
                    }
                    #endregion
                }
                else if(n==2)
                {
                    ZD();
                }
                
            }
        }
        void ZD()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(200, 200);
                this.Location = new Point(260, 260);
            }
        }
        void ShowMsg(string str)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action<string>(s =>
                {
                    txtLog.AppendText(s + "\r\n");
                }), str);
            }
            else
            {
                //txtLog.Text = str + "\r\n"+txtLog.Text;
                txtLog.AppendText(str + "\r\n");
            }
        }
    }
}
